package agents.behaviours;

import weka.core.Instances;
import agents.ClassifierAgent;
import jade.core.behaviours.TickerBehaviour;
import jade.domain.DFService;
import jade.domain.FIPAException;
import jade.domain.FIPANames;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.ServiceDescription;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.UnreadableException;
import jade.wrapper.ControllerException;

public class GetDataBehaviour extends TickerBehaviour {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	
	private String attribute;		
	
	
	public GetDataBehaviour(ClassifierAgent a, long period,String attribute) {
		super(a, period);
		this.attribute = attribute;
	}

	@Override
	protected void onTick() {
		DFAgentDescription query = new DFAgentDescription();
		ServiceDescription sd = new ServiceDescription();
		try {
			sd.setType(myAgent.getContainerController().getContainerName());
		} catch (ControllerException e) {
			throw new RuntimeException(e);
		}
		query.addServices(sd);
		try {
			DFAgentDescription[] result= DFService.search(myAgent, query);
			if(result.length!=0){
				ACLMessage msg = new ACLMessage(ACLMessage.INFORM_IF);
				msg.addReceiver(result[0].getName());
				msg.setContent(attribute);
				msg.setProtocol(FIPANames.InteractionProtocol.FIPA_QUERY);
				myAgent.send(msg);
				ACLMessage repl = myAgent.blockingReceive();
				if(repl.getPerformative() == ACLMessage.INFORM){
					Instances instances = (Instances) repl.getContentObject();
					((ClassifierAgent)myAgent).updateModel(instances);					
				}
				
			}else{
				block(1000);
			}
		} catch (FIPAException | UnreadableException e1) {
			throw new RuntimeException(e1);
		}
	}
}
